<?php
/**
 * Created by PhpStorm
 * User: lcz
 * Date: 2019/10/23
 * Time: 10:39
 * 战区
 */

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\AgentChain;
use app\common\model\AgentShipment;
use app\common\model\AgentShop;
use app\common\model\ChainFunds;
use app\common\model\ChainSon;
use think\Db;
use think\Exception;

class Chain extends Api {
	
	/**
	 * 统计
	 */
	public function statistics() {
		$userId = $this->auth->id;
		$agentInfo = Db::name('agentChain')
			->where(['user_id' => $userId])
			->find();
		if(!$agentInfo || $agentInfo['status'] == AgentChain::STATUS_DISABLED) {
			$this->error('当前身份已被禁用');
		}
		
		$shopIds = Db::name('chainSon')->where(['user_id' => $userId])->column('agent_shop_id', 'id');
		$userIds = Db::name('agentShop')->where(['id' => ['in', $shopIds]])->column('user_id', 'id');
		
		$promotion = Db::name('promotion')->where(['recommend_user_id' => ['in', $userIds]])->count();
		
		$count = Db::name('chainSon')->alias('s')
			->join('agentShop a', 's.agent_shop_id = a.id', 'left')
			->where(['s.user_id' => $userId])
			->field('sum(a.sale_number) as sale_number, sum(a.order_number) as order_number, sum(a.sale_amount) as sale_amount')
			->find();
		
		$commission = Db::name('chainFunds')->where(['user_id' => $userId])->sum('amount');
		
		$this->success('查询成功', [
			'warehouse' => count($shopIds),
			'promotion' => $promotion,
			'commission' => $commission,
			'sale_number' => $count['sale_number'] ? : 0,
			'order_number' => $count['order_number'] ? : 0,
			'sale_amount' => $count['sale_amount'] ? : 0,
		]);
	}
	
	
	/**
	 * 下级所有列表
	 */
	public function agentMap() {
		$model = new AgentShop();
		$rows = $model->where(['theater_id' => $this->auth->id])->select();
		$this->success('查询成功', $rows);
	}
	
	/**
	 * 排行
	 */
	public function ranking() {
		
		$userId = $this->auth->id;
		
		$shopIds = Db::name('chainSon')->where(['user_id' => $userId])->column('agent_shop_id', 'id');
		$userIds = Db::name('agentShop')->where(['id' => ['in', $shopIds]])->column('user_id', 'id');
		
		$promotion= Db::name('promotion')->alias('p')
			->join('user u', 'u.id = p.user_id', 'left')
			->order(['p.sale_number' => 'desc'])
			->where(['p.recommend_user_id' => ['in', $userIds]])
			->limit(10)
			->field('p.name, u.nickname, p.sale_number')
			->select();
		
		$warehouse = Db::name('agentShop')->alias('p')
			->join('user u', 'u.id = p.user_id', 'left')
			->order(['p.sale_number' => 'desc'])
			->where(['p.role' => \app\admin\model\User::LEVEL_WAREHOUSE, 'p.id' => ['in',$shopIds]])
			->limit(10)
			->field('u.nickname, p.sale_number, p.name')
			->select();
		
		$this->success('查询成功', [
			'promotion' => $promotion,
			'warehouse' => $warehouse,
		]);
	}
	
	/**
	 * 加入
	 */
	public function join() {
		$level = $this->auth->level;
		
		if($level == \app\admin\model\User::LEVEL_USER) {
			$this->error('请先入驻为提货点', [], 2);
		}
		
		if($level != \app\admin\model\User::LEVEL_WAREHOUSE) {
			$this->error('你不是提货点');
		}
		
		$chainUserId = $this->request->post('user_id', '', 'intval');
		!$chainUserId && $this->error('参数错误');
		
		$userId = $this->auth->id;
		
		if($chainUserId == $userId) {
			$this->error('不能加入自己的邀请');
			
		}
		$agentInfo = Db::name('agentShop')->where(['user_id' => $userId])->find();
		!$agentInfo && $this->error('你不是代理');
		
		$row = Db::name('chainSon')->where(['agent_shop_id' => $agentInfo['id']])->find();
		$row && $this->error('您已经加入其它连锁');
		
		$parentAgent = Db::name('agentShop')->where(['user_id' => $chainUserId])->find();
		if(!$parentAgent || $parentAgent['role'] != \app\admin\model\User::LEVEL_WAREHOUSE) {
			$this->error('分享人不是提货点');
		}
		
		if($parentAgent['chain_user_id'])	 {
			$this->error('分享人已加入其它连锁店');
		}
		
		
		$model = new ChainSon();
		$model->startTrans();
		try {
			$chain = Db::name('agentChain')->where(['user_id' => $chainUserId])->find();
			if(!$chain) {
				$chainRes = Db::name('agentChain')->insert([
					'user_id' => $chainUserId,
					'create_time' => time(),
					'update_time' => time(),
					'number' => 1
				]);
				if(!$chainRes) {
					throw new Exception('添加连锁出错');
				}
				
				$chainId = Db::name('agentChain')->getLastInsID();
			} else {
				$numRes = Db::name('agentChain')->where(['id' => $chain['id']])->setInc('number');
				if(!$numRes) {
					throw new Exception('添加连锁数量出错');
				}
				$chainId = $chain['id'];
			}
			
			$sonRes = $model->isUpdate(false)
				->save([
					'agent_chain_id' => $chainId,
					'user_id' => $chainUserId,
					'agent_shop_id' => $agentInfo['id']
				]);
			if(!$sonRes) {
				throw new Exception('添加资料出错');
			}
			
			
			
			//更改代理资料中的归属连锁店
			$agentRes = Db::name('agentShop')->where(['user_id' => $userId])->update(['chain_user_id' => $chainUserId]);
			if(!$agentRes) {
				throw new Exception('绑定连锁店出错');
			}
			$model->commit();
			$this->success('加入成功');
		} catch (Exception $e) {
			$model->rollback();
			$this->error($e->getMessage());
		}
	}
	
	
	/**
	 * 佣金详情
	 */
	public function warehouse() {
		$userId = $this->auth->id;
		
		$sons = Db::name('agentShop')
			->where(['chain_user_id' => $userId])
			->field('id, name')
			->select();
		if($sons) {
			$date = $this->request->post('date');
			
			$where['user_id'] = $userId;
			if($date) {
				$date = $date.'-01';
				$startTime = strtotime($date);
				$endTime = strtotime('+1 months', $startTime);
				$where['create_time'] = [
					['egt', $startTime],
					['lt', $endTime]
				];
			}
			
			foreach ($sons as &$son) {
				$where['agent_id'] = $son['id'];
				$funds = Db::name('chainFunds')->where($where)
					->group('type')
					->column('sum(amount) as amount', 'type');
				$son['son_amount'] = $funds[1] ??  0;
				$son['warehouse_amount'] = $funds[2] ?? 0;
				$son['destory_amount'] = $funds[3] ?? 0;
			}
		}
		
		$this->success('查询成功', $sons);
	}
	
	/**
	 * 佣金明细
	 */
	public function funds() {
		$userId = $this->auth->id;
		$page = $this->request->post('page', 1, 'intval');
		
		$count = Db::name('chainFunds')->alias('f')
			->where(['f.user_id' => $userId])
			->count();
		
		$rows = Db::name('chainFunds')->alias('f')
			->join('agentShop a', 'f.agent_id = a.id', 'left')
			->join('order o', 'f.order_id = o.id', 'left')
			->join('orderGoods og', 'f.order_id = og.order_id', 'left')
			->where(['f.user_id' => $userId])
			->order(['f.create_time' => 'desc'])
			->field('f.id, f.amount, a.name, og.goods_info, f.type, from_unixtime(f.create_time, \'%Y/%m/%d\') as date, og.number')
			->page($page)
			->select();
		
		if($rows) {
			$typeList = ChainFunds::$typeList;
			foreach ($rows as &$row) {
				$goodsInfo = json_decode($row['goods_info'], true);
				$row['goods_name'] = $goodsInfo['name'];
				$row['spec_name'] = $goodsInfo['spec_name'];
				$row['type_text'] = $typeList[$row['type']];
				unset($row['goods_info']);
			}
		}
		
		$this->success('查询成功', [
			'total' => $count,
			'page' => $page,
			'list' => $rows
		]);
	}
}
